package com.js.rtu.mvp.present;


import android.util.Log;

import com.js.rtu.RTUApplication;
import com.js.rtu.base.BasePresenter;
import com.js.rtu.fragment.third.DebugReadBean;
import com.js.rtu.mvp.bean.Cmd02Bean;
import com.js.rtu.mvp.bean.base.CommonBean;
import com.js.rtu.util.BleUtils;
import com.js.rtu.util.CollectionGroupUtil;
import com.js.rtu.util.SPUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 09多条补调数据解析
 * Created by wz on 2019/5/17.
 */
public class Cmd09Presenter implements BasePresenter<List<Cmd02Bean>> {

    int index;
    @Override
    public CommonBean<List<Cmd02Bean>> paseData(String msg) {
        Log.e("xxxx", msg);
        CommonBean<List<Cmd02Bean>> bean = new CommonBean<>();


        index= 0;
        String[] data = msg.split(" ");
        if (getDataByIndex(data, 0).equals("EE") && getDataByIndex(data, 1).equals("EE")
                && getDataByIndex(data, data.length - 1).equals("FF")
                && getDataByIndex(data, data.length - 2).equals("FF")) {

            //帧头、CRC、帧尾
            bean.setStart(getDataByIndex(data, 0) + getDataByIndex(data, 1));
            bean.setCRC(getDataByIndex(data, data.length - 4) + getDataByIndex(data, data.length - 3));
            bean.setEnd(getDataByIndex(data, data.length - 1) + getDataByIndex(data, data.length - 2));
            index = 2;//2字节

            //address
            StringBuilder str_address = new StringBuilder();
            for (int i = 0; i < 8; i++) {
                str_address.append(getDataByIndex(data, index + i));
            }
            index += 8;//8字节
            String address = BleUtils.hexStr2Str(str_address.toString());
            bean.setAddress(address);


            //length固定长度2，hex
            int length = BleUtils.hToint(getDataByIndex(data, 1) + getDataByIndex(data, index));
            index += 2;//2字节
            bean.setLength(length);


            //cmd固定长度1
            int cmd = Integer.parseInt(getDataByIndex(data, index));
            index += 1;//1字节
            bean.setCmd(cmd);

            //数据组数
            int dataNumber = BleUtils.hToint(getDataByIndex(data, index));
            index += 1;//1字节

            //每组数据长度
            int total = BleUtils.hToint(getDataByIndex(data, index));
            index += 1;//1字节
            int total2 = (data.length - index - 4) / dataNumber;

            if (total != total2) {
                total = total2;
            }
            List<String> dataList = new ArrayList<>();

            for (int i = 0; i < dataNumber; i++) {
                StringBuilder stringBuilder = new StringBuilder();
                for (int j = 0; j < total; j++) {
                    int num = index + j;
                    stringBuilder.append(getDataByIndex(data, num)).append(" ");
                }
                index += total;
                dataList.add(stringBuilder.toString());
            }
            List<Cmd02Bean> beanList = new ArrayList<>();
            for (String s : dataList) {
                data = s.split(" ");
                Cmd02Bean cmd02Bean = new Cmd02Bean();
                getTime(data, 0, cmd02Bean);
                for (int i = 6; i < data.length; i++) {
                    String start = getDataByIndex(data, i).toUpperCase();
                    i += 1;
                    int dataLength = BleUtils.hToint(getDataByIndex(data, i));

                    switch (start) {
                        case "0C":
                            List<String> OCList = new ArrayList<>();
                            for (int k = 0; k < dataLength; k++) {
                                //2字节一个整形数，低位在前
                                OCList.add(String.valueOf(BleUtils.hToint(getDataByIndex(data, 2 + i) + getDataByIndex(data, 1 + i))));
                                i += 2;
                            }
                            cmd02Bean.setOCList(OCList);
                            break;
                        case "0F":
                            List<String> OFList = new ArrayList<>();
                            for (int k = 0; k < dataLength; k++) {
                                //4字节一个浮点数，低位在前，转换成byte再取对应位数
                                OFList.add(BleUtils.byte2Float(getDataByIndex(data, 4 + i) + getDataByIndex(data, 3 + i)
                                        + getDataByIndex(data, 2 + i) + getDataByIndex(data, 1 + i)));
                                i += 4;
                            }
                            cmd02Bean.setOFList(OFList);
                            break;

                        case "0A":
                            List<String> OAList = new ArrayList<>();
                            for (int k = 0; k < dataLength; k++) {
                                //2字节一个整形数，低位在前
                                OAList.add(String.valueOf(BleUtils.hToint(getDataByIndex(data, 2 + i) + getDataByIndex(data, 1 + i))));
                                i += 2;
                            }
                            cmd02Bean.setOAList(OAList);
                            break;
                        case "0D":
                            List<String> ODList = new ArrayList<>();
                            //1byte8位，每位代表一个开关量，如03-->0000 0011 di0=1,di1=1;
                            //长度除8向上取整，即是byte的长度
                            float number = dataLength / 8.0f;
                            int count = (int) Math.ceil(number);
                            for (int l = 0; l < count; l++) {
                                //转二进制, 补齐8位
                                String di = BleUtils.toBinary(BleUtils.hToint(getDataByIndex(data, 1 + i)), 8);
                                i++;//下一组8bit
                                for (int k = 0; k < di.length(); k++) {
                                    if (dataLength != 0) {
                                        ODList.add(di.substring(di.length() - 1 - k, di.length() - k));
                                        dataLength--;//剩余读取开关量数减一
                                    }
                                }
                            }
                            cmd02Bean.setODList(ODList);
                            break;
                        case "0B":
                            //每通道长整型数据 4 字节整型，
                            List<String> OBList = new ArrayList<>();
                            for (int k = 0; k < dataLength; k++) {
                                OBList.add(String.valueOf(BleUtils.hToint(getDataByIndex(data, 4 + i) + getDataByIndex(data, 3 + i)
                                        + getDataByIndex(data, 2 + i) + getDataByIndex(data, 1 + i))));
                                i += 4;
                            }
                            cmd02Bean.setOBList(OBList);
                            break;
                        case "0E":
//                            List<String> OEList = new ArrayList<>();
//                            for (int k = 0; k < dataLength; k++) {
//                                OEList.add(String.valueOf(BleUtils.hToint(getDataByIndex(data, 2 + i) + getDataByIndex(data, 1 + i))));
//                                i += 2;
//                            }
//                            cmd02Bean.setOEList(OEList);
                            break;
                    }
                }
                Log.e("xxxx", cmd02Bean.toString());
                beanList.add(cmd02Bean);
            }


            bean.setData(beanList);
        }

        return bean;

    }

    private String getDataByIndex(String[] data, int index) {
        StringBuilder stringBuilder = new StringBuilder();
        if (index < data.length ) {
            stringBuilder.append(data[index]).append(" ");
        } else {
            this.index = data.length - 1;
        }
        if (stringBuilder.length()>0) {
            return stringBuilder.substring(0, stringBuilder.length() - 1);
        }else {
            return stringBuilder.toString();
        }
    }


    /**
     * 获取补调时间
     *
     * @param data      数据
     * @param index     下标
     * @param cmd02Bean 保存数据的实体
     */
    private void getTime(String[] data, int index, Cmd02Bean cmd02Bean) {

        //上次自报时间
        String str_time = "20" +
                BleUtils.hToint(getDataByIndex(data, index)) + "/" +
                String.format(Locale.CHINA, "%02d",
                        BleUtils.hToint(getDataByIndex(data, index + 1))) +
                "/" +
                String.format(Locale.CHINA, "%02d",
                        BleUtils.hToint(getDataByIndex(data, index + 2))) +
                " " +
                String.format(Locale.CHINA, "%02d",
                        BleUtils.hToint(getDataByIndex(data, index + 3))) +
                ":" +
                String.format(Locale.CHINA, "%02d",
                        BleUtils.hToint(getDataByIndex(data, index + 4))) +
                ":" +
                String.format(Locale.CHINA, "%02d",
                        BleUtils.hToint(getDataByIndex(data, index + 5)));
        cmd02Bean.setTime(str_time);

    }


    public String setInfo(CommonBean<List<Cmd02Bean>> bean) {
        String line = "-----------------------------------------------------------\n";
        List<Cmd02Bean> data = bean.getData();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder
                .append(String.format("指令:%s\n", bean.getCmd()))
                .append(String.format("地址:%s\n", bean.getAddress()))
                .append(line);

        float ai1 = (float) SPUtils.get(RTUApplication.getAppContext(), "ai1", 600f);
        float ai2 = (float) SPUtils.get(RTUApplication.getAppContext(), "ai2", 600f);
        float ai3 = (float) SPUtils.get(RTUApplication.getAppContext(), "ai3", 600f);
        float ai4 = (float) SPUtils.get(RTUApplication.getAppContext(), "ai4", 600f);
        float power = (float) SPUtils.get(RTUApplication.getAppContext(), "power", 3.7f);
        List<Float> aiList = new ArrayList<>();

        aiList.add(ai1);
        aiList.add(ai2);
        aiList.add(ai3);
        aiList.add(ai4);

        int num = 0;
        for (Cmd02Bean datum : data) {
            int aiNum = 0;
            num++;
            stringBuilder
                    .append(String.format("第%s组:\n", num))
                    .append(String.format("时间:%s\n", datum.getTime()));

            List<String> oaList = datum.getOAList();
            if (oaList != null && oaList.size() > 0) {
                stringBuilder
                        .append(String.format("%s\n", ">>>>>>>>模拟量数据<<<<<<<<"));
                for (int i = 0; i < oaList.size(); i++) {
                    float d = Float.parseFloat(oaList.get(i));
                    if (i == 0) {
                        //第一个CSQ
                        d = (d - 800) / 3200 * 255;//（信号强度值*3200）/255+800
                        if (d <= 0) {
                            d = 0;
                        }
                        if (d >= 255) {
                            d = 255;
                        }
                        stringBuilder.append(String.format(Locale.CHINA, "CSQ:%s(%.1f)\n", oaList.get(i), d));
                    } else if (i == (oaList.size() - 2)) {
                        //倒数第二个电池电压
                        d = (d - 800) / 3200 * power;//AD：800-4000对应0-3.7
                        if (d <= 0) {
                            d = 0;
                        }
                        if (d >= power) {
                            d = power;
                        }
                        stringBuilder.append(String.format(Locale.CHINA, "电池电压:%s(%.1f)\n", oaList.get(i), d));
                    } else if (i == (oaList.size() - 1)) {
                        //倒数第一个温度
                        d = (d - 800) / 3200 * 100;//AD：800-4000对应0-100度
                        if (d <= 0) {
                            d = 0;
                        }
                        if (d >= 100) {
                            d = 100;
                        }
                        stringBuilder.append(String.format(Locale.CHINA, "温度:%s(%.1f)\n", oaList.get(i), d));
                    } else {
                        if (aiNum >= aiList.size()) {
                            d = (d - 800) / 3200 * 600;//AD：800-4000对应0-100度
                            if (d <= 0) {
                                d = 0;
                            }
                            if (d >= 600) {
                                d = 600;
                            }

                        } else {
                            d = (d - 800) / 3200 * aiList.get(aiNum);//AD：800-4000对应0-100度
                            if (d <= 0) {
                                d = 0;
                            }
                            if (d >= aiList.get(aiNum)) {
                                d = aiList.get(aiNum);
                            }
                        }
                        stringBuilder.append(String.format(Locale.CHINA, "AI[%s]:%s(%.1f)\n", aiNum, oaList.get(i), d));
                        aiNum++;
                    }
                }

                stringBuilder.append(line);
            }


            List<String> oFList = datum.getOFList();
            if (oFList != null && oFList.size() != 0) {
                stringBuilder
                        .append(String.format("%s\n", ">>>>>>>>浮点数数据<<<<<<<<"));
                //6个一组
                List<List<String>> groupList = CollectionGroupUtil.groupListByQuantity(oFList, 6);
                for (int g = 0; g < groupList.size(); g++) {
                    stringBuilder
                            .append(String.format("Flow[%s]:%s\n", g, groupList.get(g).toString()));
                }
                stringBuilder.append(line);
            }

//            List<String> ofList = datum.getOFList();
//            if (ofList != null && ofList.size() > 0) {
//                stringBuilder
//                        .append(String.format("%s\n", ">>>>>>>>浮点数数据<<<<<<<<"));
//                stringBuilder
//                        .append(String.format("FL[0-%s]:", ofList.size() - 1));
//                stringBuilder.append(String.format("%s;\n", datum.getOFList().toString()));
//                stringBuilder.append(line);
//            }

            List<String> oDList = datum.getODList();
            if (oDList != null && oDList.size() > 0) {
                stringBuilder
                        .append(String.format("%s\n", ">>>>>>>>开关量数据<<<<<<<<"));
                for (int i = 0; i < oDList.size(); i++) {
                    stringBuilder.append(String.format("DI[%s]:%s\n", i, oDList.get(i)));
                }
            }


            List<String> obList = datum.getOBList();
            if (obList != null && obList.size() > 0) {
                stringBuilder
                        .append(String.format("%s\n", ">>>>>>>>长整型数据<<<<<<<<"));
                for (int i = 0; i < obList.size(); i++) {
                    stringBuilder.append(String.format("长整型%s:%s\n", i, obList.get(i)));
                }
            }


            List<String> oeList = datum.getOEList();
            if (oeList != null && oeList.size() > 0) {
                stringBuilder
                        .append(String.format("%s\n", ">>>>>>>>开关量连续运行时间数据<<<<<<<<"));
                for (int i = 0; i < oeList.size(); i++) {
                    stringBuilder.append(String.format("连续运行时间%s:%s\n", i, oeList.get(i)));
                }
            }

            List<String> ocList = datum.getOCList();
            if (ocList != null && ocList.size() > 0) {
                stringBuilder
                        .append(String.format("%s\n", ">>>>>>>>COD数据<<<<<<<<"));
                for (int i = 0; i < ocList.size(); i++) {
                    stringBuilder.append(String.format("COD%s:%s\n", i, ocList.get(i)));
                }

            }
            stringBuilder.append(line);

        }
        EventBus.getDefault().post(new DebugReadBean(stringBuilder.toString()));

        return stringBuilder.toString();

    }


    public List<String> export(CommonBean<List<Cmd02Bean>> bean) {
        List<String> mList = new ArrayList<>();
        List<Cmd02Bean> data = bean.getData();

        float ai1 = (float) SPUtils.get(RTUApplication.getAppContext(), "ai1", 600f);
        float ai2 = (float) SPUtils.get(RTUApplication.getAppContext(), "ai2", 600f);
        float ai3 = (float) SPUtils.get(RTUApplication.getAppContext(), "ai3", 600f);
        float ai4 = (float) SPUtils.get(RTUApplication.getAppContext(), "ai4", 600f);
        float power = (float) SPUtils.get(RTUApplication.getAppContext(), "power", 3.7f);
        List<Float> aiList = new ArrayList<>();
        int aiNum = 0;
        aiList.add(ai1);
        aiList.add(ai2);
        aiList.add(ai3);
        aiList.add(ai4);
        for (Cmd02Bean datum : data) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder

                    .append(String.format("地址:%s", bean.getAddress())).append(",")
                    .append(String.format("时间:%s", datum.getTime())).append(",");

            List<String> oaList = datum.getOAList();
            if (oaList != null && oaList.size() > 0) {
                for (int i = 0; i < oaList.size(); i++) {
                    float d = Float.parseFloat(oaList.get(i));
                    if (i == 0) {
                        //第一个CSQ
                        d = (d - 800) / 3200 * 255;//（信号强度值*3200）/255+800
                        if (d <= 0) {
                            d = 0;
                        }
                        if (d >= 255) {
                            d = 255;
                        }
                        stringBuilder.append(String.format(Locale.CHINA, "CSQ:%s(%.1f)", oaList.get(i), d)).append(",");
                    } else if (i == (oaList.size() - 2)) {
                        //倒数第二个电池电压
                        d = (d - 800) / 3200 * power;//AD：800-4000对应0-3.7
                        if (d <= 0) {
                            d = 0;
                        }
                        if (d >= power) {
                            d = power;
                        }
                        stringBuilder.append(String.format(Locale.CHINA, "电池电压:%s(%.1f)", oaList.get(i), d)).append(",");
                    } else if (i == (oaList.size() - 1)) {
                        //倒数第一个温度
                        d = (d - 800) / 3200 * 100;//AD：800-4000对应0-100度
                        if (d <= 0) {
                            d = 0;
                        }
                        if (d >= 100) {
                            d = 100;
                        }
                        stringBuilder.append(String.format(Locale.CHINA, "温度:%s(%.1f)", oaList.get(i), d)).append(",");
                    } else {
                        if (aiNum >= aiList.size()) {
                            d = (d - 800) / 3200 * 600;//AD：800-4000对应0-100度
                            if (d <= 0) {
                                d = 0;
                            }
                            if (d >= 600) {
                                d = 600;
                            }

                        } else {
                            d = (d - 800) / 3200 * aiList.get(aiNum);//AD：800-4000对应0-100度
                            if (d <= 0) {
                                d = 0;
                            }
                            if (d >= aiList.get(aiNum)) {
                                d = aiList.get(aiNum);
                            }
                        }

                        stringBuilder.append(String.format(Locale.CHINA, "AI[%s]:%s(%.1f)", aiNum, oaList.get(i), d)).append(",");
                        aiNum++;
                    }
                }


            }

            List<String> ofList = datum.getOFList();

            for (int i = 0; i < ofList.size(); i++) {
                stringBuilder
                        .append(String.format("FL[%s]:%s", i, ofList.get(i))).append(",");
            }


            List<String> oDList = datum.getODList();
            if (oDList != null && oDList.size() > 0) {
                for (int i = 0; i < oDList.size(); i++) {
                    stringBuilder.append(String.format("DI[%s]:%s", i, oDList.get(i))).append(",");
                }
            }


            List<String> obList = datum.getOBList();
            if (obList != null && obList.size() > 0) {

                for (int i = 0; i < obList.size(); i++) {
                    stringBuilder.append(String.format("长整型%s:%s", i, obList.get(i))).append(",");
                }
            }


            List<String> oeList = datum.getOEList();
            if (oeList != null && oeList.size() > 0) {

                for (int i = 0; i < oeList.size(); i++) {
                    stringBuilder.append(String.format("连续运行时间%s:%s", i, oeList.get(i))).append(",");
                }
            }

            List<String> ocList = datum.getOCList();
            if (ocList != null && ocList.size() > 0) {
                for (int i = 0; i < ocList.size(); i++) {
                    stringBuilder.append(String.format("COD%s:%s", i, ocList.get(i))).append(",");
                }

            }

            mList.add(stringBuilder.toString());
//            HistoryBean.insertHistory("09", 3, "解析成功", stringBuilder.toString());
        }

        return mList;
    }
}





